package shopping

import (
	"dhfshop/models/shopping"
	"time"
	"strconv"
	"github.com/pkg/errors"
	//"github.com/astaxie/beego"
	"dhfshop/controllers/base"
	"github.com/astaxie/beego/validation"
)

// 评价管理
type ReviewController struct {
	base.BaseController
}


func (this *ReviewController) PubList() {
	query,_,fields,order_by,offset,limit,err := this.GetQueryPara()
	if err != nil {
	   this.ServeError(err.Error())
	   return
	}
	l, cnt, err := shopping.GetAllReviews(query,fields,order_by,offset,limit)
	if err != nil {
	    this.ServeError(err.Error())
	    return
	}
	r := struct {
		TotalCount   int64     `json:"total_count"`
		Review    []*shopping.Review `json:"review"`
	}{TotalCount: cnt, Review: l}
	this.Data["json"] = r
	this.ServeJSON()
}

func (this *ReviewController) Post() {
	var (
		v shopping.Review
		err error
	)
	valid := validation.Validation{}
	this.ParseForm(&v)
	passed, _ := valid.Valid(&v)
	if !passed {
		this.ServeError(valid.Errors[0].Key+" "+valid.Errors[0].Message)
		return	
	}
	v.PartnerId = int64(this.Ctx.Input.GetData("curCompanyId").(int))
	if v.OrderId, err = strconv.ParseInt(v.OrderIdStr, 10, 64); err != nil {
	    this.ServeError(err.Error())
		return
	}
	order, err := shopping.GetOrderById(v.OrderId)
	if err != nil {
	    err = errors.Wrap(err, "GetOrderById... ")
		this.ServeError(err.Error())
		return
	}
	v.MemberId = order.MemberId
	if v.ItemId, err = strconv.ParseInt(v.ItemIdStr, 10, 64); err != nil {
	    this.ServeError(err.Error())
		return
	}
	if v.SkuId, err = strconv.ParseInt(v.SkuIdStr, 10, 64); err != nil {
	    this.ServeError(err.Error())
		return
	}
	if _, err = shopping.AddReview(&v); err != nil {
        this.ServeError(err.Error())
		return
    }
	rsp := struct {
		ReviewId  int64      `json:"review_id"`
	    Created   time.Time  `json:"created"`
	}{ReviewId: v.ReviewId, Created:time.Now().UTC()}
	this.Data["json"] = rsp
	this.ServeJSON()
}

